package com.villaday.idf.activity;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.appcompat.widget.Toolbar;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.villaday.idf.R;
import com.villaday.idf.adapter.CustomerListAdapter;
import com.villaday.idf.base.AbsRecyclerViewAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.base.OnAdapterCallbackListener;
import com.villaday.idf.custom.LoadingDialog;
import com.villaday.idf.custom.DividerItemDecoration.RVItemDecoration;
import com.villaday.idf.model.RefreshtokenEntity;
import com.villaday.idf.model.VipsMembersEntity;
import com.villaday.idf.util.BitMapUtil;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogeUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.PhoneUtil;
import com.villaday.idf.util.ToolBarUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * 客户列表
 */
public class CustomerListActivity extends BaseActivity implements SwipeRefreshLayout.OnRefreshListener, AbsRecyclerViewAdapter.OnItemClickListener, OnAdapterCallbackListener, OkHttpUtil.OnDataListener
        , AbsRecyclerViewAdapter.OnBtnListener {

    @BindView(R.id.toolbar_icon)
    Toolbar toolbar;
    @BindView(R.id.rv)
    RecyclerView rv;
    @BindView(R.id.srl)
    SwipeRefreshLayout srl;
    @BindView(R.id.tv_install_app)
    TextView tvInstallApp;
    Unbinder unbinder;
    private LoadingDialog loadingDialog;
    private Gson gson = new GsonBuilder().create();

    private int pageNo = 1;
    private int nextIndex = 1;
    private int pageSize = 20;
    List<VipsMembersEntity.BodyBean.ListBean> data = new ArrayList();
    private CustomerListAdapter customerListAdapter;
    RefreshtokenEntity.BodyBean.MemberBean.InviteShareBean refreshtoken;


    @Override
    protected int getViewResId() {
        return R.layout.activity_customer_behavior;
    }

    @Override
    protected void init() {
        ToolBarUtil.initToolBar(toolbar, "1".equals(getIntent().getStringExtra("memberType")) ? "粉丝列表" : "团队列表", new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        }, R.drawable.icon_search, new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startActivity(new Intent(CustomerListActivity.this, CustomerListSvipActivity.class).putExtra("memberType", getIntent().getStringExtra("memberType")));
            }
        });
        tvInstallApp.setVisibility(View.GONE);
        srl.setOnRefreshListener(this);
        rv.setLayoutManager(new LinearLayoutManager(this));
        customerListAdapter = new CustomerListAdapter(this, this);
        rv.setAdapter(customerListAdapter);

        rv.addItemDecoration(new RVItemDecoration(LinearLayout.VERTICAL, PhoneUtil.dp2px(this, 1), getResources().getColor(R.color.colorBg), PhoneUtil.dp2px(this, 1)));
        customerListAdapter.setOnItemClickListener(this);
        customerListAdapter.setOnBtnListener(this);
 /*       View inflate = View.inflate(this, R.layout.item_head_income_details, null);
        customerListAdapter.addHeaderView(inflate);*/
        customerListAdapter.setEmptyView2(R.layout.empty_customer_tips, true, R.id.tv_perchase);
        customerListAdapter.setEmptyTips(R.id.tv_emptyTips, "1".equals(getIntent().getStringExtra("memberType")) ? "没有更多了" : "暂时还没有下级,现在开始累积也不晚");
        customerListAdapter.setEmptyBtn(R.id.tv_perchase, "1".equals(getIntent().getStringExtra("memberType")) ? "去转发商品" : "去邀请好友成为VIP");
        loadingDialog = LoadingDialog.newInstance("加载中...");
        loadingDialog.show(getFragmentManager());
    }

    @Override
    protected void loadData() {
        getData();
    }

    private void getData() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNo", pageNo + "");
        map.put("pageSize", pageSize + "");
        map.put("memberType", getIntent().getStringExtra("memberType"));
        OkHttpUtil.getJSON(this, Constant.URL.vips_members, map, this);
    }

    @Override
    public void onRefresh() {
        pageNo = 1;
        nextIndex = 1;
        getData();
    }

    //rv item 点击事件
    @Override
    public void onItemClick(View v, int position) {
/*        Intent intent = new Intent(this, FindDetailsActivity.class);
        intent.putExtra("topicId", data.get(position).getId());
        startActivity(intent);*/
    }

    @OnClick({R.id.tv_install_app, R.id.tv_inquire_start_time, R.id.tv_inquire_end_time, R.id.tv_select_btn})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.tv_install_app: {  //安装App

            }
            break;
            case R.id.tv_inquire_start_time: {  //开始时间

            }
            break;
            case R.id.tv_inquire_end_time: {  //结束时间

            }
            break;
            case R.id.tv_select_btn: {  //查询

            }
            break;
        }

    }

    @Override
    public void onCallback() {
        if (nextIndex == pageNo + 1) {
            pageNo++;
            getData();
        }
    }

    @Override
    public void onResponse(String url, String json) {
        if (Constant.URL.vips_members.equals(url)) {
            LogeUtil.e("vips_members", json);
            dismissLoading();
            VipsMembersEntity vmEntity = gson.fromJson(json, VipsMembersEntity.class);
            removeLoadingItem();
            if (pageNo == 1) {
                data.clear();
            }

            if ("200".equals(vmEntity.getCode())) {
                   /* if (pageNo == 1 && presellEntity.getBody().getRecomendList() != null && presellEntity.getBody().getRecomendList().getList() != null) {

                        dataHead.addAll(presellEntity.getBody().getRecomendList().getList());
                        homeListSaleHeadAdapter.setData(dataHead);
                    }*/
                data.addAll(vmEntity.getBody().getList());
                if (vmEntity.getBody().isHasNext()) {
                    data.add(new VipsMembersEntity.BodyBean.ListBean(1));
                    nextIndex = pageNo + 1;

                } else {
                    addBaseLine();
                }

            } else {
                addBaseLine();
            }
            customerListAdapter.setData(data);
//            customerListAdapter.setData(null);
        }
    }

    @Override
    public void onFailure(String url, String error) {

    }

    private void dismissLoading() {

        if (srl != null && srl.isRefreshing()) {
            srl.setRefreshing(false);
        }
        if (loadingDialog != null) {
            loadingDialog.dismiss();
        }

    }

    private void removeLoadingItem() {
        if (data.size() > 0) {
            if (data.get(data.size() - 1).getMyType() == 1) {
                data.remove(data.size() - 1);
            }
        }
    }

    private void addBaseLine() {
        if (pageNo != 1) {
            data.add(new VipsMembersEntity.BodyBean.ListBean(2));
        }
    }

    @Override
    public void function() {
        switch (getIntent().getStringExtra("memberType")) {
            case "1":
                setResult(Activity.RESULT_OK);
                finish();
                break;

            case "2": //下级客户订单

          /*      refreshtoken = gson.fromJson(getIntent().getStringExtra("shareBean"), RefreshtokenEntity.BodyBean.MemberBean.InviteShareBean.class);
                ShareDialog shareDialog = ShareDialog.newInstance();
                shareDialog.show(getFragmentManager());
                shareDialog.setOnItemClickListener(new BaseDialog.OnItemClickListener() {
                    @Override
                    public void onItemClick(View v) {
                        switch (v.getId()) {
                            case R.id.tv_Swx: {
                                saveImageToSdCard(CustomerListActivity.this, refreshtoken.getImageURL());
                                share(0);
                            }
                            break;
                            case R.id.tv_Spyq: {
                                saveImageToSdCard(CustomerListActivity.this, refreshtoken.getImageURL());
                                share(1);

                            }
                            break;
                            case R.id.tv_Ssave: {
                                saveImageToSdCard(CustomerListActivity.this, refreshtoken.getImageURL());
                                share(2);
                            }
                            break;
                        }
                    }
                });*/
            /*    Intent intent = new Intent(this, SVIPLibaoAndFreeActivity.class);
                intent.putExtra("type", 0);
                startActivity(intent);*/
                startActivity(new Intent(this, SVIPFreeActivity.class));
                break;

            case "3":
                startActivity(new Intent(this, InviteLiBaoActivity.class));
                break;


        }

    }


    private void share(int i) {
        String imageFileName = IMAGE_NAME + ".jpg";
        File externalCacheDir = getExternalCacheDir();
        String fileName = externalCacheDir.getPath() + "/" + imageFileName;
        String sharefileName = externalCacheDir.getPath() + "/12306" + imageFileName;
        WXWebpageObject webpage = new WXWebpageObject();
        webpage.webpageUrl = refreshtoken.getLinkURL();
        WXMediaMessage msg = new WXMediaMessage(webpage);
        msg.title = refreshtoken.getTitle();
        msg.description = refreshtoken.getDesc();
        Bitmap bitmap = BitMapUtil.getBitmap(fileName);
        /*Bitmap bitmap1 = BitMapUtil.compressBitmap(bitmap, 31*1024);
        BitMapUtil.saveBitmap2File(bitmap1,sharefileName);
        Bitmap bitmap2 = BitMapUtil.getBitmap(sharefileName);*/
        //Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.mipmap.share);
        msg.thumbData = BitMapUtil.compressBitmap(bitmap, 31 * 1024);
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = "webpage";
        req.message = msg;
        req.scene = i == 0 ? SendMessageToWX.Req.WXSceneSession : i == 1 ? SendMessageToWX.Req.WXSceneTimeline : SendMessageToWX.Req.WXSceneFavorite;
        IWXAPI api = WXAPIFactory.createWXAPI(this, Constant.ID.WeChat_APP_ID, false);
        api.sendReq(req);

    }

    public static String IMAGE_NAME = "shareVip";

    //根据网络图片url路径保存到本地
    public File saveImageToSdCard(Context context, String image) {
        boolean success = false;
        File file = null;
        try {
            file = createStableImageFile(context);
            Bitmap bitmap = null;
            URL url = new URL(image);
            HttpURLConnection conn = null;
            conn = (HttpURLConnection) url.openConnection();
            InputStream is = null;
            is = conn.getInputStream();
            bitmap = BitmapFactory.decodeStream(is);
            FileOutputStream outStream;

            outStream = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
            outStream.flush();
            outStream.close();
            success = true;
            //MediaStore.Images.Media.insertImage(context.getContentResolver(), image, file.getName(), "你对图片的描述");

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (success) {

            return file;
        } else {
            return null;
        }
    }

    //创建本地保存路径
    public static File createStableImageFile(Context context) throws IOException {
        String imageFileName = IMAGE_NAME + System.currentTimeMillis() + ".jpg";
        File storageDir = context.getExternalCacheDir();
        File image = new File(storageDir, imageFileName);
        return image;
    }


}
